<?php
/**

  * 围绕办事处包的一系列的操作

  * @version 0.1

  */
class ectools_office_operation
{
    /**

      * @var object 应用实例对象

      */
    private $app;

    /**

      * @var object 模型实例

      */
    private $model;

    /**
      * @var array 办事处数组

      */
    public $office;

    /**

      * 构造方法

      * @param object 当前app的

      * @return null
      */
    public function __construct($app)
    {
        $this->app = $app;
        $this->model = $this->app->model('office');
    }

     /**
     * 主要用于后台显示，判断当前的数据是否超过100，显示方式不同
     * @params null
     * @return boolean
     */
    public function getTreeSize()
    {
        $cnt = $this->model->count();
	//edit by peter 2017-03-22 固定返回true,使用树形视图(原来为>100)
        if ($cnt >= 0)
            return true;
        else
            return false;
    }

    /**
     * 获取指定parent office id的下级办事处数量
     * @params string office id
     * @return int 数量
     */
    private function getChildCount($office_id)
    {
        //$row = $this->db->selectrow('select count(*) as childCount from '.$this->table_name(1).' where p_office_id='.intval($office_id));
        $cnt = $this->model->count(array('p_office_id' => intval($office_id)));
        //return $row['childCount'];
        return $cnt;
    }

    /**
     * 得到办事处信息 - parent office id， 层级，下级办事处
     * @params string office id
     * @return array 指定信息的数组
     */
    public function getOfficeById($officeId='')
    {
        //$sql='select office_id,p_office_id,local_name,ordernum,office_path from '.$this->table_name(1).' as r where r.p_office_id'.($officeId?('='.intval($officeId)):' is null').' order by ordernum asc,office_id asc';
        //$aTemp=$this->db->select($sql);
        if ($officeId)
            $aTemp = $this->model->getList('office_id,p_office_id,local_name,default_local,limited_amount,ordernum,office_path', array('p_office_id' => $officeId), 0, -1, 'ordernum ASC,office_id ASC');
        else
            $aTemp = $this->model->getList('office_id,p_office_id,local_name,default_local,limited_amount,ordernum,office_path', array('office_grade' => '1'), 0, -1, 'ordernum ASC,office_id ASC');

        if (is_array($aTemp)&&count($aTemp) > 0)
        {
            foreach($aTemp as $key => $val)
            {
                $aTemp[$key]['p_office_id']=intval($val['p_office_id']);
                $aTemp[$key]['step'] = intval(substr_count($val['office_path'],','))-1;
                $aTemp[$key]['child_count'] = $this->getChildCount($val['office_id']);
            }
        }
 
        return $aTemp;
    }

    /**
     * 得到办事处的结构图
     * @params int parent office id
     * @return array 结构图数组
     */
    public function getMap($prId='')
    {
        if ($prId)
            $sql="select office_id,office_grade,local_name,ordernum,limited_amount,(select count(*) from ".$this->model->table_name(1)." where p_office_id=r.office_id) as child_count from ".$this->model->table_name(1)." as r where r.p_office_id=".intval($prId)." order by ordernum asc,office_id";
        else
            $sql="select office_id,office_grade,local_name,ordernum,limited_amount,(select count(*) from ".$this->model->table_name(1)." where p_office_id=r.office_id) as child_count from ".$this->model->table_name(1)." as r where r.p_office_id is null order by ordernum asc,office_id";

        $row = $this->model->db->select($sql);

        if (isset($row) && $row)
        {
            foreach ($row as $key => $val)
            {
                $this->office[] = array(
                    "local_name"=>$val['local_name'],
                    "office_id"=>$val['office_id'],
                    "office_grade"=>$val['office_grade'],
                    "ordernum"=>$val['ordernum'],
                    "limited_amount"=>$val['limited_amount'],
                );

                if ($val['child_count'])
                    $this->getMap($val['office_id']);
            }
        }
    }

    /**
     * 新建修改信息
     * @params array - 请求的数据信息
     * @params string - message
     */
    public function insertDlArea($aData,&$msg)
    {

        if (!trim($aData['local_name']))
        {
            $msg = app::get('ectools')->_('办事处名称不能为空！');
            return false;
        }

        $aData['ordernum'] = $aData['ordernum'] ? $aData['ordernum'] : '50';
        if ($this->model->checkDlArea($aData['local_name'], $aData['p_office_id']))
        {
            $msg = app::get('ectools')->_('该办事处名称已经存在！');
            return false;
        }

        //$tmp = $this->model->db->selectrow('select office_path from '.$this->model->table_name(1).' where office_id='.intval($aData['p_office_id']));
        $tmp = $this->model->dump(intval($aData['p_office_id']), 'office_path');
        if (!$tmp)
            $tmp['office_path'] = ",";

        $office_path = $tmp['office_path'];
        $aData = array_filter($aData);

        if ($this->model->save($aData))
        {
            $officeId = $this->model->db->lastInsertId();
            $tmp = $this->model->dump($officeId, '*');
            $tmp['office_path'] = $office_path . $officeId . ',';
            $tmp['office_grade'] = count(explode(",", $tmp['office_path'])) - 2;
            if($this->model->save($tmp)) {
                return $this->updateOfficeData();
            }
            return false;
        }
        else
        {
            return false;
        }
        
    }

    /**
     * 更改办事处信息
     * @params array - 新的办事处的信息的数组
     * @params string - 更新结果消息
     */
    public function updateDlArea($aData,&$msg)
    {
        $is_save = false;

        if ($aData['office_id'] == $aData['p_office_id'])
        {
            $msg = app::get('ectools')->_('上级办事处不能为本位置！');
            return false;
        }
        else
        {
            $idGroup = $this->model->getGroupOfficeId($aData['office_id']);
            if ($idGroup)
            {
                if (in_array($aData['p_office_id'],$idGroup)){
                    $msg = app::get('ectools')->_('上级办事处不能为本位置的子办事处！');
                    return false;
                }
            }
        }

        if(!$aData['office_id'])
        {
            $msg = app::get('ectools')->_('参数丢失！');
            return false;
        }
        else
        {
            $cPath = $this->model->dump(intval($aData['office_id']), 'office_path');
        }

        if (!trim($aData['local_name']))
        {
            $msg = app::get('ectools')->_('办事处名称不能为空！');
            return false;
        }

        if (intval($aData['p_office_id']))
        {
            $tmp = $this->model->dump(intval($aData['p_office_id']), 'office_path');
            $aData['office_path'] = $tmp['office_path'].$aData['office_id'].",";
        }
        else
        {
            $aData['office_path'] = ",".$aData['office_id'].",";
        }

        $aData['ordernum'] = isset($aData['ordernum']) ? $aData['ordernum'] : '50';
        $aData['office_grade'] = count(explode(",",$aData['office_path'])) - 2;
        $aData = array_filter($aData);
        $is_save = $this->model->save($aData);

        if(($is_save && $this->updateSubPath($cPath['office_path'],$aData['office_path']))) {
            return $this->updateOfficeData();
        }
        return false;
    }

    /**
     * 删除指定id的办事处信息
     * @params int office id
     * @return boolean 删除成功与否
     */
    public function toRemoveArea($officeId)
    {
        //$tmpRow = $this->model->db->selectrow("select office_path from ".$this->table_name(1)." where office_id=".intval($officeId));
        $tmpRow = $this->model->dump(intval($officeId), 'office_path,local_name');

        //$this->db->exec("DELETE FROM ".$this->table_name(1)." where office_id=".intval($officeId));
        $this->model->delete(array('office_id' => intval($officeId)));
        #↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓记录管理员操作日志@lujy↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
	//edit by peter 2017-03-21
        /*if($obj_operatorlogs = kernel::service('operatorlog.system')){
            if(method_exists($obj_operatorlogs,'removeArea')){
                $obj_operatorlogs->removeArea($tmpRow['local_name']);
            }
        }
	*/
        #↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑记录管理员操作日志@lujy↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
        // 删除相应的所有的下级办事处
        if($this->toRemoveSubArea($tmpRow['office_path'])) {
            return $this->updateOfficeData();
        }
        return false;
    }

    /**
     * 删除指定的级别的区域
     * @params string 层级字符串
     * @return boolean 删除是否成功
     */
    private function toRemoveSubArea($path)
    {
        if ($path)
        {
            return $this->model->db->exec("DELETE FROM ".$this->model->table_name(1)." where office_path LIKE '".$path."%'");
        }
    }

    /**
     * 更新下级办事处的path值
     * @params string 上级的office_path
     * @params string 下一级办事处的office_path
     * @return boolean 更新结果
     */
    private function updateSubPath($Opath,$Npath)
    {
        $offset = count(explode(",",$Npath)) - count(explode(",",$Opath));

        return $this->model->db->exec("update ".$this->model->table_name(1)." set office_path=replace(office_path,".$this->model->db->quote($Opath)
            .",".$this->model->db->quote($Npath)."),office_grade=office_grade + "
            .intval($offset)." where office_path LIKE '%".$Opath."%'");
    }

    private function getAllOffice($p_officeid='', $pkey='', &$office_count=array()) {
        $show_depth = $this->app->getConf('system.area_depth');
        if ($p_officeid)
            $sql="select office_id,office_grade,local_name,ordernum,(select count(*) from ".$this->model->table_name(1)." where p_office_id=r.office_id) as child_count from ".$this->model->table_name(1)." as r where r.p_office_id=".intval($p_officeid)." order by ordernum asc,office_id";
        else
            $sql="select office_id,office_grade,local_name,ordernum,(select count(*) from ".$this->model->table_name(1)." where p_office_id=r.office_id) as child_count from ".$this->model->table_name(1)." as r where r.p_office_id is null order by ordernum asc,office_id";

        $row = $this->model->db->select($sql);

        if (isset($row) && $row)
        {
            $cur_row = current($row);
            if(!$office_count[$cur_row['office_grade']]) {
                $start_index = 0;
            }
            else {
                $start_index = $office_count[$cur_row['office_grade']];
            }
            foreach ($row as $key => $val)
            {
                $tmp = array(
                    $val['local_name'],
                    $val['office_id'],
                );
                $index = $pkey!==''?$pkey:$key;
                if($val['child_count']) {
                    if($val['office_grade']<$show_depth) {
                        $tmp[] = $start_index;
                    }
                    $start_index++;
                    $office_count[$cur_row['office_grade']] = $start_index;
                }
                if($val['office_grade'] != 1) {
                    $this->office[$val['office_grade']][$index][] = implode(":", $tmp);
                }
                else {
                    $this->office[$val['office_grade']][$index] = implode(":", $tmp);
                }
                if ($val['child_count'] && $val['office_grade']<$show_depth) {
                    $this->getAllOffice($val['office_id'], $start_index-1, $office_count);
                }
            }
        }
    }

    /**
     * 更新office控件JS数据
     * @reutrn boolean
     */
    public function updateOfficeData() {
        $this->getAllOffice();
        $this->office = (array)$this->office;

        $office = array();
        foreach($this->office as $v) {
            $office[] = $v;
        }
        unset($this->office);

        // 文件数据
        $str = "var office_Data='".json_encode($office)."';\r\n";
        $str .= "office_Data = eval('(' + office_Data + ')');";
        if(ECAE_MODE){
            $this->app->setConf('system.office_data',$str);
        }else{
            // 文件名字
            $filename = DATA_DIR.'/misc/office_data.js';
            $handle = fopen($filename, "w");
            if(!$handle) {
                fclose($handle);
                return false;
            }
            if(!fwrite($handle, $str)) {
                fclose($handle);
                return false;
            }
            fclose($handle);
        }
        return true;
    }
}
